package com.plian.Tools;

import com.plian.Tools.pagedata.PageData;
import com.plian.Tools.file.FileMeta;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class UpFilesUtil {
	public static Map<String, PageData> UpFiles(MultipartHttpServletRequest request, HttpServletRequest req,
                                                String url) {
		// TODO 自动生成的构造函数存根
		// 文件保存
		Map<String, MultipartFile> mp = request.getFileMap();
		Map<String, PageData> files = new PageData();
		if (mp.size() > 0) {
			for (String key : mp.keySet()) {

				MultipartFile mpf = mp.get(key);
				FileMeta fileMeta = null;
				if (mpf != null) {
					PageData pdd = new PageData();

					Date date = new Date();
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
					String time = format.format(date);
					if (mpf.getOriginalFilename() != "") {
						pdd.put("name", mpf.getOriginalFilename() + time);
						pdd.put("size", mpf.getSize() / 1024 + " Kb");
						pdd.put("url", req.getRealPath("uploadFiles/" + url));
						files.put(key, pdd);
						fileMeta = new FileMeta();

						fileMeta.setFileName(mpf.getOriginalFilename());
						fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
						fileMeta.setFileType(mpf.getContentType());
						try {
							fileMeta.setBytes(mpf.getBytes());
							CreateFileUtil.createDir(req.getRealPath("uploadFiles/" + url));
							String path = req.getRealPath("uploadFiles/" + url);

							mpf.transferTo(new File(path, mpf.getOriginalFilename() + time));
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return files;

	}


	public static Map<String, PageData> UpFiles(MultipartHttpServletRequest request, HttpServletRequest req,
                                                String url, boolean a) {
		// TODO 自动生成的构造函数存根

		Map<String, MultipartFile> mp = request.getFileMap();
		Map<String, PageData> files = new PageData();
		if (mp.size() > 0) {
			for (String key : mp.keySet()) {
				MultipartFile mpf = mp.get(key);
				FileMeta fileMeta = null;
				if (mpf != null) {
					PageData pdd = new PageData();
					if (mpf.getOriginalFilename() != "") {
						pdd.put("name", mpf.getOriginalFilename());
						pdd.put("size", mpf.getSize() / 1024 + " Kb");
						pdd.put("url", url);
						files.put(key, pdd);
						fileMeta = new FileMeta();

						fileMeta.setFileName(mpf.getOriginalFilename());
						fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
						fileMeta.setFileType(mpf.getContentType());
						try {
							fileMeta.setBytes(mpf.getBytes());
							CreateFileUtil.createDir(url);
							String path = url;

							mpf.transferTo(new File(path, mpf.getOriginalFilename()));
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return files;

	}

	/**
	 *文件下载
	 * @param name 文件名，包含拓展名
	 * @param url 文件保存路径 不包含文件名
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public static void DownFile(String name, String url, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 设置响应头和客户端保存文件名
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String n = name.substring(0, name.length() - 19);
		String na = new String(n.getBytes("utf-8"), "iso-8859-1");
		response.setHeader("Content-Disposition", "attachment;fileName=" + na);

		// 打开本地文件流
		InputStream inputStream = new FileInputStream(url + "/" + name);
		// 激活下载操作
		OutputStream os = response.getOutputStream();

		// 循环写入输出流
		byte[] b = new byte[2048];
		int length;
		while ((length = inputStream.read(b)) > 0) {
			os.write(b, 0, length);

		}

		// 这里主要关闭。
		os.close();
		inputStream.close();

	}


	/**
	 * 根据byte数组，生成文件
	 */
	public static void getFile(byte[] bfile, String filePath,String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath+"\\"+fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);


			bos.write(bfile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static int parse(String s) {
		char c[] = s.toCharArray();
		String ss = "";
		for (int i = 0; i < c.length; i++) {
			if (c[i] >= '0' && c[i] <= '9') {
				ss += c[i];
			}
		}
		return Integer.parseInt(ss);
	}

}
